package site.wenneng.dev.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.stereotype.Service;
import site.wenneng.dev.service.BaseService;
import site.wenneng.dev.objs.po.DefineProjectPO;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RemoteService extends BaseService {

    @SneakyThrows
    public List<DefineProjectPO> queryProjectFromRemote(List<Integer> productIdList) {
        String payload = "{\"product_ids\":[" + productIdList.stream().map(Object::toString).collect(Collectors.joining(",")) + "]}";
        Request request = new Request.Builder()
                .url("https://dev.hundsun.com/heppm/project/fuzzySearchInvolvedProjects")
                .post(RequestBody.create(payload, MediaType.parse("application/json")))
                .build();
        ObjectMapper objectMapper = getObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(invoke(request));
        JsonNode codeNode = jsonNode.get("code");
        if (codeNode == null || !codeNode.textValue().equals("200")) {
            log.error("请求失败：{}", jsonNode.toPrettyString());
            throw new RuntimeException("请求失败：" + jsonNode.toPrettyString());
        }
        return objectMapper.readValue(jsonNode.get("data").traverse(), new TypeReference<List<DefineProjectPO>>() {
        });
    }
}
